package com.medication.config;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;

import org.joda.time.DateTime;

import com.jfinal.kit.PropKit;
import com.medication.utils.Currents;

public class PlatformLoaderListener implements ServletContextListener, ServletRequestListener {

	@Override
	public void requestDestroyed(ServletRequestEvent arg0) {
		// TODO Auto-generated method stub
	}

	@Override
	public void requestInitialized(ServletRequestEvent sre) {
		ServletRequest request = sre.getServletRequest();
		DateTime dateTime = DateTime.now();
		request.setAttribute(Currents.CURRENT_DATE_TIME_KEY, dateTime.toString("yyyy-MM-dd hh24:mm:ss"));
		request.setAttribute(Currents.CURRENT_DATE_KEY, dateTime.toString("yyyy-MM-dd"));
		request.setAttribute(Currents.CURRENT_MONTH_KEY, dateTime.getMonthOfYear());
		request.setAttribute(Currents.CURRENT_YEAR_KEY, dateTime.getYear());
	}

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {

	}

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		// 设置系统属性加载到ServletContext的appConfig属性里面
		loadProp("config.txt", "configdev.txt");

		ServletContext servletContext = sce.getServletContext();
		servletContext.setAttribute(ServletContextHolder.APP_CONFIG_KEY,
				PropKit.get(ServletContextHolder.APP_CONFIG_KEY));
		// 设置ctx
		String contextPath = sce.getServletContext().getContextPath();
		servletContext.setAttribute(ServletContextHolder.CONTEXT_PATH_KEY, contextPath);
		// 资源文件请求路径
		// String appVersion = PropKit.get(ServletContextHolder.APP_CONFIG_KEY))(Configuration.APP_VERSION_KEY);
		servletContext.setAttribute(ServletContextHolder.RESOURCE_PATH_KEY, contextPath + "/resources");
		ServletContextHolder.setServletContext(servletContext);
	}

	public void loadProp(String pro, String dev) {
		try {
			PropKit.use(pro);
		} catch (Exception e) {
			PropKit.use(dev);
		}
	}

}
